package com.drore.app.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/14 16:33
 */

public class CheckPermissionUtil {
    public static int PERMISSON_REQUEST_CODE = 200;

    /**
     * 检测权限
     *
     * @param mContext   文本
     * @param permission 要检查的权限
     * @return boolean
     */
    public static boolean chechPermission(final Context mContext, String permission) {
        return chechPermission(mContext, permission, false, null);
    }

    /**
     * 检测权限
     *
     * @param mContext      文本
     * @param permission    要检查的权限
     * @param isNeedRequest 没有权限是否申请
     * @param tip           申请提示，是什么权限
     * @return boolean
     */
    public static boolean chechPermission(final Context mContext, String permission, boolean isNeedRequest, String tip) {
        if (ContextCompat.checkSelfPermission(mContext, permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (isNeedRequest) {
                requestPermission(mContext, permission, tip);
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 申请权限
     *
     * @param mContext   文本
     * @param permission 权限
     * @param tip        "申请存储权限"
     */
    public static void requestPermission(final Context mContext, final String permission, String tip) {
        // 第一次请求权限时，用户如果拒绝，下一次请求shouldShowRequestPermissionRationale()返回true
        // 向用户解释为什么需要这个权限
        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, permission)) {
            new AlertDialog.Builder(mContext)
                    .setMessage(tip)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //申请相机权限
                            ActivityCompat.requestPermissions((Activity) mContext,
                                    new String[]{permission}, PERMISSON_REQUEST_CODE);
                        }
                    })
                    .show();
        } else {
            //申请权限
            ActivityCompat.requestPermissions((Activity) mContext,
                    new String[]{permission}, PERMISSON_REQUEST_CODE);
        }

    }

}
